define([
	"UtilDir/util",
	"UtilDir/tool",
    "UtilDir/org/selectOrg",
    "UtilDir/searchBlock",
	"UtilDir/loading",
	"Date","DateCN", "css!DateCss",
	"EasyUI","EasyUI-lang"
    ],function(Util, Tool, SelectOrg, SearchBlock, Loading){

	var getBoundaryController = function () {
		return getServer() + "/boundary";
	};
	var getFxCertaintyLossDistrictsController = function(){
		return getServer() + "/fxEconomyLossMiddles";
	};
	var getFxBuildingsController = function(){
		return getServer() + "/fxBuildingss";
	}
	var getFxCasulatyEstimateController = function () {
		return getServer() + "/fxCasulatyEstimates";
	};

	/**
	 * 页面初始化
	 */
	var init = function(){
        initSearchBlock();
        queryBtnBind();
		initProvinceSelect("北京市", "北京市", "");
		formValidator();
		initMap();
	};

	var initProvinceSelect = function (Province, City, Area) {
		//debugger;
		var html = "";
		$("#citySelect").append(html);
		$("#areaSelect").append(html);
		$.ajax({
			url: getServer() +"/divisions/root/subdivisions",
			contentType: "application/json",
			type: "get",
			success: function (data) {
				$.each(data, function (idx, item) {
					if (item.divisionName == Province) {
						//debugger;
						var divisionId = item.divisionId;
						var htmlCity = '';
						if (Province == "北京市" || Province == "天津市" || Province == "上海市" || Province == "重庆市") {
							$("#citySelect").append("<option value='" + Province + "' exid='" + divisionId + "'>" + Province + "</option>");
							$('#citySelect').val(City);
							var htmlArea = '';
							$.ajax({
								url: getServer() +"/divisions/" + divisionId + "/subdivisions",
								contentType: "application/json",
								type: "get",
								success: function (data) {
									$.each(data, function (idx, item) {
										htmlArea += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
									});
									$("#areaSelect").append(htmlArea);
									$('#areaSelect').val(Area);
									// 列表
									//queryFxCertaintyLossDistrictsData();
								}
							});

						} else {
							$.ajax({
								url: getServer() +"/divisions/" + divisionId + "/subdivisions",
								contentType: "application/json",
								type: "get",
								success: function (data) {
									debugger;
									$.each(data, function (idx, item) {
										if (item.divisionName == City) {
											var divisionId = item.divisionId;
											var htmlArea = '';
											$.ajax({
												url: getServer() +"/divisions/" + divisionId + "/subdivisions",
												contentType: "application/json",
												type: "get",
												success: function (data) {
													$.each(data, function (idx, item) {
														htmlArea += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
													});
													$("#areaSelect").append(htmlArea);
													$('#areaSelect').val(Area);
												}
											});
										}
										htmlCity += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
									});
									$("#citySelect").append(htmlCity);
									$('#citySelect').val(City);
								}
							});
						}
					}
					html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
				});
				$("#provinceSelect").append(html);
				$('#provinceSelect').val(Province);
			}
		});
		$("#provinceSelect").change(function () {
			var html = '<option value="" disabled selected style="display:none;">请选择</option>';
			$("#citySelect option").remove();
			$("#citySelect").append(html);
			$("#areaSelect option").remove();
			$("#areaSelect").append(html);
			var divisionId = $(this).find("option:selected").attr("exid");
			if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
				$("#citySelect").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).val() + "</option>");
				return;
			}
			$.ajax({
				url: getServer() +"/divisions/" + divisionId + "/subdivisions",
				contentType: "application/json",
				type: "get",
				success: function (data) {
					$.each(data, function (idx, item) {
						html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
					});
					$("#citySelect").append(html);
				}
			});
		});
		$("#citySelect").change(function () {
			if ($(this).val() == "") return;
			var html = '<option value="" disabled selected style="display:none;">请选择</option>';
			$("#areaSelect option").remove();
			$("#areaSelect").append(html);
			var divisionId = $(this).find("option:selected").attr("exid");
			$.ajax({
				url: getServer() +"/divisions/" + divisionId + "/subdivisions",
				contentType: "application/json",
				type: "get",
				success: function (data) {
					$.each(data, function (idx, item) {
						html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
					});
					$("#areaSelect").append(html);
				}
			});
		});
	};
	var initSearchBlock = function(){
        SearchBlock.init("searchBlock");
	};
	var formValidator = function(){
		$("#searchForm").validate({
			rules : {
				provinceSelect : {
					required : true,
				},
				citySelect : {
					required : true,
				}
			},
			messages : {
				provinceSelect : {
					required : "省不允许为空!",
				},
				citySelect : {
					required : "市不允许为空!",
				}
			}
		});
	};
	var queryBtnBind = function(){
        $("#btnSearch").click(function () {
			queryFxCertaintyLossDistrictsData();
        });
        $("#btnReset").click(function () {
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#citySelect option").remove();
			$("#citySelect").append(html);
			$("#areaSelect option").remove();
			$("#areaSelect").append(html);
            initProvinceSelect("北京市", "北京市", "");
		});
		$("#btnExport").click(function () {
			Util.alert("功能暂未实现");
		});
	};
	var queryFxCertaintyLossDistrictsData= function() {
		tdMap.clearOverLays();
		var province = $("#provinceSelect").val() || "", city = $("#citySelect").val() || "", area = $("#areaSelect").val() || "";
		var intensity = $("#fx-CLD-intensity-radio-div input[type=radio]:checked").val(),
			period = $("#fx-CLD-period-radio-div input[type=radio]:checked").val(),
			casulaty = $("#fx-CLD-casulaty-radio-div input[type=radio]:checked").val();
		loading.show();
		$.ajax({
			url: getFxCasulatyEstimateController() + "/listFxCasulatyEstimates?province=" + province + "&city=" + city + "&area=" + area + "&intensity=" + intensity + "&period=" + period + "&casulaty=" + casulaty,
			type: "get",
			success: function (data) {
				console.log(data);
				global_points = []; global_areaIsFinished = {};
				if (data && data.length) {
					var area2cValue = {}, fixedValue;
					for (let i = 0; i < data.length; i++) {
						fixedValue = (!data[i].fixedValue ? 0 : data[i].fixedValue);
						!area2cValue[data[i].area] ? (area2cValue[data[i].area] = parseInt(fixedValue)) : (area2cValue[data[i].area] += parseInt(fixedValue));
					}
					console.log(area2cValue);
					for (let areaName in area2cValue) {
						global_areaIsFinished[areaName] = false;
						renderDistrictByEvaluation(area2cValue[areaName], province, city, areaName);
					}
				} else {
					Util.alert("查询无数据!");
				}
			}
		});
    };
	var renderDistrictByEvaluation = function (evaluation, province, city, areaName) {
		var formData = {province: province, city: city, area: areaName};
		$.ajax({
			url: getBoundaryController() + "/getSingleAreaBoundary",
			type: "POST",
			data: formData,
			success: function (coords) {
				//console.log(coords);
				global_areaIsFinished[areaName] = true;
				if (coords && coords != "") {
					coords = coords[areaName];
					var _coords = coords.split("|");
					for (let k = 0; k < _coords.length; k++) {
						var lonlats = _coords[k].split(";"), lonlat, lon = 0, lat = 0, points = [];
						for (var i = 0;i < lonlats.length;i++) {
							lonlat = lonlats[i].split(",");
							lon = parseFloat(lonlat[0]); lat = parseFloat(lonlat[1]);
							points.push(new T.LngLat(lon, lat));
						}
						global_points = global_points.concat(points);
						var color = getPolygonColorByValue(evaluation);
						console.log(evaluation, "color: ", color);
						var areaPolygon = new T.Polygon(points, {
							color: "#0000ff",
							weight: 1,
							opacity: 0.5,
							fillColor: color,
							fillOpacity: 0.7
						});
						tdMap.addOverLay(areaPolygon);
					}
					taskIsFinish(global_areaIsFinished) && (tdMap.setViewport(global_points), loading.close(), console.log("********"));
				} else {
					loading.close();
					Util.alert("【" + province + city + areaName + "】无边界数据!");
				}
			}
		});
	};
	var getPolygonColorByValue = function (value) {
		var rank, i = 0;
		for (i = 0; i < color_rank.length; i++) {
			rank = color_rank[i];
			if (value >= rank[0] && value < rank[1]) break;
		}
		return rank_color[i + ""];
	};
	var taskIsFinish = function (obj) {
		for (var _key in obj) if (!obj[_key]) return false;
		return true;
	}
	var color_rank = [[0, 5], [5, 10], [10, 30], [30, 50], [50, 100], [100, 200], [200, 500], [500, 1000], [1000, 2000], [2000, 5000], [5000, 10000], [1000, Infinity]];
	var rank_color = {"0": "#82027B", "1": "#0B52A4", "2": "#00967B",
					  "3": "#7FC41C", "4": "#FFBF01", "5": "#FF4401",
					  "6": "#13017B", "7": "#008738", "8": "#FF7F00",
					  "9": "#FEFF00", "10": "#01A1C5", "11": "#FF0103"};
	var loading = Loading({text : "正在查询数据..."});
	var tdMap, global_points = [], global_areaIsFinished = {};
	var initMap = function () {
		var mapH = document.body.clientHeight - $(".pd-search-container").height() - 20;
		$("#fx-CLD-data-mapDiv").height(mapH);

		var vec_layer = new T.TileLayer("https://fxpc.mem.gov.cn/data_preparation/171dd1d5-bbb3-483a-a7f6-50d6d98cee1f/d9ffc071-50dd-4780-a617-673d17921e22/wmts?service=wmts&request=gettile&version=1.0.0&layer=vec&style=default&tilematrixset=c&format=tiles&tilematrix={z}&tilerow={y}&tilecol={x}&geokey=94E99EB4FEB9B48CD5348F7BCF5BB620");
		var cva_layer = new T.TileLayer("https://fxpc.mem.gov.cn/data_preparation/171dd1d5-bbb3-483a-a7f6-50d6d98cee1f/13f8b69d-98dc-4276-bbf0-9c4c372acabc/wmts?service=wmts&request=gettile&version=1.0.0&layer=cva&style=default&tilematrixset=c&format=tiles&tilematrix={z}&tilerow={y}&tilecol={x}&geokey=94E99EB4FEB9B48CD5348F7BCF5BB620");
		var config = {
			projection: 'EPSG:4326',
			minZoom: 4,
			layers: [vec_layer, cva_layer]
		};
		tdMap = new T.Map('fx-CLD-data-mapDiv', config), zoom = 4;
		tdMap.centerAndZoom(new T.LngLat(106.34766, 34.37971), zoom);
	};

	return {
		init:init
	};
});
